package com.zhoug.zmui.dialog.list;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.zhoug.common.adapters.BaseListViewAdapter;
import com.zhoug.common.utils.AppUtils;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.StringUtils;
import com.zhoug.zmui.R;
import com.zhoug.zmui.group.ZMUIListView;
import com.zhoug.zmui.utils.ZMUIUtils;
import com.zhoug.zmui.ints.OnMultiSelectedListener;
import com.zhoug.zmui.utils.DialogAttributeParser;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;

/**
 * 多选列表对话框
 * zmui_style_ZMUIMultiSelectListDialog
 * 定义全局样式
 * @Author 35574
 * @Date 2020/7/21
 * @Description
 */
public abstract class ZMUIMultiSelectListDialog<T> extends ZMUIAbsListDialog<T> {
    private static final String TAG = ">>>ZMUISelectListDialog";
    private static final boolean DEBUG = true;
    /**
     * 选择的item position
     */
    private List<Integer> mSelected = new ArrayList<>();
    /***临时存储选择,便于重置**/
    private List<Integer> cacheSelected = new ArrayList<>();
    /**
     * 选择监听
     */
    private OnMultiSelectedListener onMultiSelectedListener;
    /**
     * checkbox的位子
     */
    private int checkImageGravity;
    public static final int LEFT = 1;
    public static final int RIGHT = 2;

    /**
     * 按钮1
     */
    private String positiveText;
    /**
     * 按钮2
     */
    private String negativeText;

    private int positiveBtnColor;
    private float positiveBtnSize;
    private int negativeBtnColor;
    private float negativeBtnSize;

    /**
     * 选中时的图片资源
     */
    private @DrawableRes
    int checkedDrawableRes;
    /**
     * 非选中时的图片资源
     */
    private @DrawableRes
    int unCheckedDrawableRes;


    // POSITIVE
    //  NEGATIVE
    //NEUTRAL
    private ZMUIListAdapter mAdapter;

    public ZMUIMultiSelectListDialog(@NonNull Context context) {
        this(context, 0);
    }

    public ZMUIMultiSelectListDialog(@NonNull Context context, int themeResId) {
        this(context, themeResId, R.attr.zmui_style_ZMUIMultiSelectListDialog, 0);
    }

    protected ZMUIMultiSelectListDialog(@NonNull Context context, int themeResId, int defStyleAttr, int defStyleRes) {
        super(context, themeResId, defStyleAttr, defStyleRes);
    }

    @Override
    protected void initialize(@NonNull Context context, int defStyleAttr, int defStyleRes) {
        checkImageGravity = RIGHT;
        super.initialize(context, defStyleAttr, defStyleRes);
        DialogAttributeParser.parseZMUIButtonDialogAttrs(this, context, defStyleAttr, defStyleRes);
        TypedArray typedArray = context.obtainStyledAttributes(null, R.styleable.ZMUIMultiSelectListDialog, defStyleAttr, defStyleRes);
        checkImageGravity=typedArray.getInt(R.styleable.ZMUIMultiSelectListDialog_zmui_checkImageGravity,RIGHT);
        checkedDrawableRes=typedArray.getResourceId(R.styleable.ZMUIMultiSelectListDialog_zmui_checkedDrawable,R.drawable.zmui_icon_checked);
        unCheckedDrawableRes=typedArray.getResourceId(R.styleable.ZMUIMultiSelectListDialog_zmui_unCheckedDrawable,R.drawable.zmui_icon_unchecked);

        typedArray.recycle();
        setTextGravity(Gravity.START);

    }


    @Override
    protected int getLayoutResId() {
        return R.layout.zmui_multi_list_dialog;
    }

    @Override
    protected void onViewCreated(Bundle savedInstanceState) {
        super.onViewCreated(savedInstanceState);
        getRootContainer().setMaxHeight(0);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);

    }

    @Override
    protected void initListView(ListView listView) {
        initButton();
        mAdapter = new ZMUIListAdapter();
        mAdapter.setData(getData());
        listView.setAdapter(mAdapter);
        if(cacheSelected.size()>0){
            scrollToSelected(cacheSelected.get(0));
        }else{
            scrollToSelected(0);
        }
        if(listView instanceof ZMUIListView){
            ((ZMUIListView) listView).setMaxHeight(getMaxHeight());
        }
    }

    /**
     * 按钮
     */
    private void initButton() {
        TextView mPositiveBtn = findViewById(R.id.btn_positive);
        View mLine2 = findViewById(R.id.line2);
        TextView mNegativeBtnBtn = findViewById(R.id.btn_negative);

        mPositiveBtn.setVisibility(View.VISIBLE);
        mNegativeBtnBtn.setVisibility(View.VISIBLE);
        mLine2.setVisibility(View.VISIBLE);

        //设置2个按钮
        //确认按钮
        ZMUIUtils.setTextColor(mPositiveBtn, positiveBtnColor);
        ZMUIUtils.setTextSize(mPositiveBtn, positiveBtnSize);
        mPositiveBtn.setText(StringUtils.isEmpty(positiveText) ? "确认" : positiveText);
        mPositiveBtn.setOnClickListener(onBtnClickListener);
        //取消按钮
        ZMUIUtils.setTextColor(mNegativeBtnBtn, negativeBtnColor);
        ZMUIUtils.setTextSize(mNegativeBtnBtn, negativeBtnSize);
        mNegativeBtnBtn.setText(StringUtils.isEmpty(negativeText) ? "取消" : negativeText);
        mNegativeBtnBtn.setOnClickListener(onBtnClickListener);
        if (positiveBtnSize != negativeBtnSize) {
            //文字大小不同时,按钮的高度会不一样
            //计算按钮的最大高度
            AppUtils.measureView(mPositiveBtn);
            AppUtils.measureView(mNegativeBtnBtn);
            int maxBtnHeight = Math.max(mPositiveBtn.getMeasuredHeight(), mNegativeBtnBtn.getMeasuredHeight());
            if (DEBUG) {
                LogUtils.d(TAG, "init:maxBtnHeight=" + maxBtnHeight);
            }
            if (maxBtnHeight > 0) {
                mPositiveBtn.setHeight(maxBtnHeight);
                mNegativeBtnBtn.setHeight(maxBtnHeight);
            }
        }

    }

    private View.OnClickListener onBtnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.btn_positive) {
                mSelected.clear();
                if(cacheSelected.size()>0){
                    //升序
                    Collections.sort(cacheSelected);
                    mSelected.addAll(cacheSelected);
                }
                if(onMultiSelectedListener!=null){
                    onMultiSelectedListener.onSelected(mSelected);
                }
            } else if (id == R.id.btn_negative) {
                cacheSelected.clear();
            }
            dismiss();
        }
    };


    /**
     * 数据适配器
     */
    private class ZMUIListAdapter extends BaseListViewAdapter<T> implements View.OnClickListener {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.zmui_mult_select_list_item, parent, false);
                TextView textView = convertView.findViewById(R.id.textView);
                ImageView checkImage = getCheckImageView(convertView);
                checkImage.setVisibility(View.VISIBLE);
                ZMUIUtils.setTextSize(textView, getTextSize());
                ZMUIUtils.setTextColor(textView, getTextColor());
                textView.setGravity(getTextGravity());

            }
            TextView textView = convertView.findViewById(R.id.textView);
            ImageView checkImage = getCheckImageView(convertView);
            T itemData = getItemData(position);
            //设置选中状态
            if (isChecked(position)) {
                checkImage.setImageResource(checkedDrawableRes);
            } else {
                checkImage.setImageResource(unCheckedDrawableRes);
            }

            if (itemData != null) {
                textView.setText(getText(itemData));
                convertView.setTag(position);
                convertView.setOnClickListener(this);
            } else {
                textView.setText(null);
                checkImage.setVisibility(View.GONE);
                convertView.setOnClickListener(null);
            }
            return convertView;
        }

        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            ImageView checkImageView = getCheckImageView(v);
            if (isChecked(position)) {
                cacheSelected.remove((Integer) position);
                checkImageView.setImageResource(unCheckedDrawableRes);
            } else {
                cacheSelected.add(position);
                checkImageView.setImageResource(checkedDrawableRes);
            }
        }

        private ImageView getCheckImageView(View convertView) {
            if (checkImageGravity == LEFT) {
                return convertView.findViewById(R.id.checkImage_left);
            } else {
                return convertView.findViewById(R.id.checkImage_right);
            }
        }
    }


    /**
     * 判断给定position是否选中
     *
     * @param position
     * @return
     */
    private boolean isChecked(int position) {
        if (cacheSelected.size() > 0) {
            for (int i = 0; i < cacheSelected.size(); i++) {
                if (cacheSelected.get(i) == position) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void show() {
        cacheSelected.clear();
        if (mSelected.size() > 0) {
            cacheSelected.addAll(mSelected);
            scrollToSelected(cacheSelected.get(0));
        }else{
            scrollToSelected(0);
        }
        super.show();

    }

    public void setOnMultiSelectedListener(OnMultiSelectedListener onMultiSelectedListener) {
        this.onMultiSelectedListener = onMultiSelectedListener;
    }

    /**
     * 设置选中
     *
     * @param selected
     */
    public void setSelected(List<Integer> selected) {
        this.mSelected.clear();
        if (selected != null && selected.size() > 0) {
            this.mSelected.addAll(selected);
        }
    }

    /**
     * 设置CheckBox的位置
     *
     * @param checkImageGravity {@link #LEFT,#RIGHT}
     */
    public void setCheckImageGravity(int checkImageGravity) {
        this.checkImageGravity = checkImageGravity;
    }


    public ZMUIMultiSelectListDialog<T> setPositiveBtnColor(int positiveBtnColor) {
        this.positiveBtnColor = positiveBtnColor;
        return this;
    }

    public ZMUIMultiSelectListDialog<T> setPositiveBtnSize(float positiveBtnSize) {
        this.positiveBtnSize = positiveBtnSize;
        return this;
    }

    public ZMUIMultiSelectListDialog<T> setNegativeBtnColor(int negativeBtnColor) {
        this.negativeBtnColor = negativeBtnColor;
        return this;
    }

    public ZMUIMultiSelectListDialog<T> setNegativeBtnSize(float negativeBtnSize) {
        this.negativeBtnSize = negativeBtnSize;
        return this;
    }

    public ZMUIMultiSelectListDialog<T> setPositiveText(String positiveText) {
        this.positiveText = positiveText;
        return this;
    }

    public ZMUIMultiSelectListDialog<T> setNegativeText(String negativeText) {
        this.negativeText = negativeText;
        return this;
    }
}
